package com.lap.permission.enums;

import com.lap.framework.enums.YesNo;
import com.lap.permission.domain.entity.DictDetail;
import com.lap.permission.tools.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

/**
 * 字典枚举
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
public enum DictEnum {
    YES {
        @Override
        List<DictDetail> getDetail(String param) {
            final String[] ps = StringUtils.split(param, Constants.COLON);
            return doExecute(ps[1]);
        }
    },
    NO {
        @Override
        List<DictDetail> getDetail(String param) {
            return doExecute(param);
        }
    },
    ;

    /**
     * 获取字典明细集合
     *
     * @param param 字典备注
     * @return 字典明细集合
     */
    public static List<DictDetail> getDictList(String param) {
        if (StringUtils.isBlank(param))
            return Collections.emptyList();

        return param.trim().contains(Constants.COLON)
                ? YES.getDetail(param)
                : NO.getDetail(param);
    }

    /**
     * 解析字符串,分解成集合
     *
     * @param param 字典备注
     * @return 字典明细集合
     */
    private static List<DictDetail> doExecute(String param) {
        if (StringUtils.isBlank(param))
            return Collections.emptyList();

        String[] array = param.split(Constants.REGULAR);
        if (ArrayUtils.isEmpty(array))
            return Collections.emptyList();

        AtomicInteger index = new AtomicInteger(0);
        return Stream.of(array)
                .filter(StringUtils::isNotBlank)
                .map(item -> getDictDetail(item, index))
                .filter(Objects::nonNull)
                .toList();
    }

    private static DictDetail getDictDetail(String item, AtomicInteger index) {
        String[] values = item.split(Constants.TEST);
        if (values.length == 2) {
            try {
                DictDetail detail = new DictDetail();
                detail.setDetailValue(Integer.valueOf(values[0]));
                detail.setDetailTitle(values[1]);
                detail.setOrders(index.incrementAndGet());
                detail.setStatusFlag(YesNo.YES.getValue());
                detail.setLocal(StringUtils.defaultIfBlank(detail.getLocal(), Lang.ZH_CN.getValue()));
                return detail;
            } catch (NumberFormatException ex) {
                log.warn("转换异常: {} ，内容详情: {}", ex.getLocalizedMessage(), item);
            }
        }
        return null;
    }

    /**
     * 根据字典备注获取明细
     *
     * @param param 字典备注
     * @return 字典明细
     */
    abstract List<DictDetail> getDetail(String param);

}
